import java.util.Arrays;

public class Heap {
    public int[] elem;
    public int usedSize;// 数组中有效元素的个数

    public Heap(){
        //this.elem = new int[10];
        //this.usedSize = 0;
    }

    public void initArray(int[] array){
        this.elem = Arrays.copyOf(array,array.length);
        usedSize = elem.length;
    }

    /**
     * 创建 大根堆
     *  时间复杂度: O(n)
     */
    public void createHeap(){
        for (int parent = (usedSize-2)/2;parent >= 0;parent--){
            shiftDown(parent,usedSize);
        }
    }

    /**
     * 向下调整
     * @param parent 每颗子树的根节点下标
     * @param len 每颗子树的结束位置
     */
    public void shiftDown(int parent,int len){
        int child = 2 * parent + 1;
        while(child < len){
            if (child+1 < len && elem[child] < elem[child+1]){
                child++;
            }
            if (elem[child] > elem[parent]){
                swap(elem,child,parent);
                parent = child;
                child = 2*parent + 1;
            }else {
                break;
            }
        }
    }

    public void swap(int[] array,int i,int j){
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    public void disPlay(){
        //System.out.println(Arrays.toString(elem));
        for (int i = 0; i < usedSize; i++) {
            System.out.print(elem[i]+" ");
        }
        System.out.println();
    }

    /**
     * 插入元素
     *   1.在最后一个结点进行插入
     *   2.向上调整
     * @param val
     */
    public void insert(int val){
        if (isFull()){
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        this.elem[usedSize] = val;
        usedSize++;
        shiftUp(usedSize-1);
    }

    public boolean isFull(){
        return elem.length == usedSize;
    }

    public void shiftUp(int child){
        int parent = (child-1) / 2;
        while(child > 0){
            if (elem[child] > elem[parent]){
                swap(elem,child,parent);
                child = parent;
                parent = (child-1) / 2;
            }else {
                break;
            }
        }
    }

    /**
     * 删除 只能是堆顶元素(要么最大,要么最小)
     */
    public void delete(){
        if (!isEmpty()) {
            swap(elem,0,usedSize-1);
            usedSize--;
            shiftDown(0,usedSize);
        }else {
            System.out.println("当前堆为空!");
        }
    }

    public boolean isEmpty(){
        return usedSize == 0;
    }

    public void heapSort(){
        int end = this.usedSize-1;
        while (end > 0){
            swap(elem,0,end);
            shiftDown(0,end);
            end--;
        }
    }
}
